import os
import re, uiautomation as auto
import sys
import time

TITLE_PATTERNS = [r'.*BOSS直聘.*']            # 标题模糊匹配
CHROME_CLASSES = {'Chrome_WidgetWin_0', 'Chrome_WidgetWin_1'}
MAX_DEPTH = 100
SEARCH_TMO = 3.0
PER_ITEM_TMO = 3.0

def list_top_windows():
    root = auto.GetRootControl()
    rows = []
    for w in root.GetChildren():
        try:
            rows.append((w.ControlTypeName, w.Name or '', w.ClassName or '', w))
        except Exception:
            pass
    for i, (t, n, c, _) in enumerate(rows, 1):
        print(f"{i:02d}. type={t:14} name='{n}' class='{c}'",file=sys.stderr)
    return rows

def name_matches(name: str) -> bool:
    return any(re.fullmatch(pat, name or '') for pat in TITLE_PATTERNS)


def get_boss_window(timeout: float = 3.0):
    """
    获取 BOSS直聘 根控件（WindowControl 或 PaneControl）
    :param timeout: 查找超时，秒
    :return: Control 对象或 None
    """
    with auto.UIAutomationInitializerInThread():
        auto.SetGlobalSearchTimeout(0.5)

        # 1) 先尝试 WindowControl（标准顶层窗口）
        win = auto.WindowControl(RegexName=r'.*BOSS直聘.*', searchDepth=1)
        if win.Exists(timeout, 0.2):
            return win

        # 2) 回退：在顶层 PaneControl 里找（Electron/Chromium 应用常见）
        root = auto.GetRootControl()
        for c in root.GetChildren():
            if 'BOSS直聘' in (c.Name or '') and c.ClassName in ('Chrome_WidgetWin_0', 'Chrome_WidgetWin_1'):
                return c

    print("❌ 未找到 BOSS直聘 窗口",file=sys.stderr)

    return None


def pick_boss_root():
    """返回最合理的 BOSS 根节点（Window 或 Pane）"""
    # 1) 先尝试 WindowControl（如果 BOSS 是真正的顶层窗口）
    for pat in TITLE_PATTERNS:
        win = auto.WindowControl(RegexName=pat, searchDepth=1)
        if win.Exists(SEARCH_TMO, 0.2):
            return win

    # 2) 回退：在顶层子控件中找 PaneControl + Class=Chrome_WidgetWin_* + Name 匹配
    tops = list_top_windows()  # 也顺便打印出来方便你核对
    candidates = []
    for _, name, cls, elem in tops:
        if cls in CHROME_CLASSES and name_matches(name):
            candidates.append(elem)

    if candidates:
        # 取面积最大者作为根
        def area(e):
            try:
                r = e.BoundingRectangle
                return max(0, (r.right - r.left)) * max(0, (r.bottom - r.top))
            except Exception:
                return -1
        return max(candidates, key=area)

    return None


def get_all_texts(root_ctrl, max_depth=None):
    """
    遍历 root_ctrl 下的所有子孙，收集 Text/Document 控件的 Name
    """
    texts = []

    def walk(ctrl, depth=0):
        if max_depth is not None and depth > max_depth:
            return
        try:
            children = ctrl.GetChildren()
        except Exception:
            return
        for c in children:
            try:
                if c.ControlTypeName in ('TextControl', 'GroupControl','HyperlinkControl'):
                    if c.Name:  # 去掉空
                        texts.append(c.Name.strip())
            except Exception:
                pass
            walk(c, depth+1)

    walk(root_ctrl)
    return texts

def is_visible(ctrl):
    try:
        if ctrl.IsOffscreen:
            return False
        r = ctrl.BoundingRectangle
        if r.right <= r.left or r.bottom <= r.top:
            return False
        # 判断是否在屏幕范围内
        from ctypes import windll
        sw = windll.user32.GetSystemMetrics(0)
        sh = windll.user32.GetSystemMetrics(1)
        if r.right <= 0 or r.bottom <= 0 or r.left >= sw or r.top >= sh:
            return False
        return True
    except Exception:
        return False

'''
消息数量: []
消息信息: ['08月12日', '李美丽', '品类运营', '[我已读]', '你好，请问还招聘吗？']
坐标 (553, 1829)


消息数量: ['1']
消息信息: ['08月12日', '姜迎迎', '品类运营', '[未读]', '您好，上班时间是怎样的？']
坐标 (553, 1965)


消息数量: ['2']
消息信息: ['08月11日', '顾路臣', '品类运营', '[未读]', '吗']
坐标 (553, 2102)
'''

from PIL import Image, ImageDraw
def crop_strict_circle(img_path, save_path):
    img = Image.open(img_path).convert("RGBA")
    width, height = img.size

    # 取最短边，裁剪成正方形
    side = min(width, height)
    left = (width - side) // 2
    top = (height - side) // 2
    img = img.crop((left, top, left + side, top + side))

    # 创建圆形掩码（半径缩小，避免外圈黑边）
    mask = Image.new('L', (side, side), 0)
    draw = ImageDraw.Draw(mask)
    margin = int(side * 0.05)  # 往里缩 5% 去掉黑边
    draw.ellipse((margin, margin, side - margin, side - margin), fill=255)

    # 应用掩码
    circular_img = Image.new('RGBA', (side, side), (0, 0, 0, 0))
    circular_img.paste(img, mask=mask)

    circular_img.save(save_path, "PNG")


def execute(win):
    with auto.UIAutomationInitializerInThread():
        if win == None:
            win = get_boss_window()
        #win = get_boss_window()  # pick_boss_root()
        win.Exists(3, 0.2)  # 超时等待


        #  获取头像
        account_right =  auto.TextControl(searchFromControl=win, Name='账号权益')
        avatar = account_right.GetParentControl().GetPreviousSiblingControl().GetFirstChildControl().GetFirstChildControl().GetFirstChildControl()
        avatar.CaptureToImage('account_avatar.png')
        # 使用
        crop_strict_circle("account_avatar.png", "account_avatar_clean.png")
        abs_path = os.path.abspath('account_avatar_clean.png')
        print(f"账号头像绝对路径:{abs_path}" ,file=sys.stdout)



        # 获取公司名称
        auto.HyperlinkControl(searchFromControl=win, Name='职位').Click()
        time.sleep(1)
        openBtn =  auto.TextControl(searchFromControl=win, Name='开放中')
        openBtn.Exists(3,3)
        openBtn.Click()
        list_item = openBtn.GetParentControl().GetParentControl().GetParentControl().GetNextSiblingControl().GetChildren()

        auto.HyperlinkControl(searchFromControl=list_item[0], Name='编辑').Click()

        # list_item[0][7].Click()
        time.sleep(3)
        company =  auto.TextControl(searchFromControl=win, Name='公       司')
        company_name = company.GetParentControl().GetNextSiblingControl().GetFirstChildControl()
        company_name = company_name.Name.split("·")[-1]
        print(f'公司名称：{company_name}',file=sys.stdout)


        # 获取职位列表
        auto.HyperlinkControl(searchFromControl=win, Name='职位').Click()
        time.sleep(1)
        openBtn =  auto.TextControl(searchFromControl=win, Name='开放中')
        time.sleep(3)
        openBtn.Click()
        list_item = openBtn.GetParentControl().GetParentControl().GetParentControl().GetNextSiblingControl().GetChildren()

        post_list = []
        # ["品类运营", "普", "淮北", "3-5年", "本科", "1-3K", "全职"]
        for item in list_item:
            value_win = item.GetChildren()[0]
            text = get_all_texts(value_win)

            result = {
                "positionName": text[0],
                "positionLevel": text[1],
                "workLocation": text[2],
                "experienceRequired": text[3],
                "educationRequired": text[4],
                "salaryRange": text[5],
                "jobType": text[6]
              }

            post_list.append(result)
            print('职位信息：',text, file=sys.stderr)


        results = {
            "postList": post_list,
            "companyName": company_name,
            "avatar": abs_path,
        }


        return results

# print('开始执行')
# results = execute(None)
# print(results)